import type { RouteLocationNormalized, Router } from "vue-router";
// import { useUserStore } from "@/store/modules/user";
// import { openNotify } from "@/hooks/web/useNotify.hook";
// import { NotifyTypeEnum } from "@/enums/notify.enum";
// import { postTokenTest } from "@/api/path/user";
// import { openLoadingView, closeLoadingView } from "@/hooks/app/viewLoading";

interface GuardResult {
    pass: boolean;
    redirect?: string;
}

type GuardFunction = (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized
) => Promise<GuardResult> | GuardResult;

export function createRouterGuards(router: Router) {
    router.beforeEach(async (to, from, next) => {
        // openLoadingView();
        const result = await performGuard(to, from);
        if (result.pass) {
            next();
        } else {
            if (result.redirect) {
                await router.replace(result.redirect);
            }
            next(false);
        }
    });
    router.afterEach(() => {
        // closeLoadingView();
    });
}

const guardMap: { [key: string]: GuardFunction } = {
    // validateLogin: (to: RouteLocationNormalized, _from: RouteLocationNormalized): GuardResult => {
    //     const mustLogin = Boolean(to.meta.mustLogin);
    //     if (!mustLogin) {
    //         return { pass: true };
    //     }
    //     const store = useUserStore();
    //     if (store.isLogin) {
    //         return { pass: true };
    //     } else {
    //         openNotify({
    //             title: "权限不足",
    //             message: "请在登录后访问该页面",
    //             type: NotifyTypeEnum.WARNING
    //         });
    //         return { pass: false };
    //     }
    // },
    // validateToken: async (
    //     to: RouteLocationNormalized,
    //     _from: RouteLocationNormalized
    // ): Promise<GuardResult> => {
    //     const mustLogin = Boolean(to.meta.mustLogin);
    //     if (!mustLogin) {
    //         return { pass: true };
    //     }
    //     const result = await postTokenTest();
    //     if (result) {
    //         return { pass: true };
    //     }
    //     openNotify({
    //         title: "会话过期",
    //         message: "请重新登录。",
    //         type: NotifyTypeEnum.WARNING
    //     });
    //     return { pass: false, redirect: "/home" };
    // }
};

const performGuard = async (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized
): Promise<GuardResult> => {
    for (const key in guardMap) {
        const guard = guardMap[key];
        const result = await guard(to, from);
        if (!result.pass) {
            return result;
        }
    }
    return { pass: true };
};
